package cn.com.winning.ecare.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.Grideviewmenu;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.expandable.ActionSlideExpandableListView;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;
import cn.com.winning.ecare.widgets.InnerListView;

/**
 * 一日清单
 * @author Administrator
 *
 */
public class Costeveryday extends Activity
{

	private ListView list_sub;
	private ActionSlideExpandableListView list_main;
	private TextView contenttv, item, reference;

	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> listsub = new ArrayList<Map<String, Object>>();
	private List<Object> children = new ArrayList<Object>();

	MyMainAdapter mainAdapter = null;
	MySubAdapter subAdapter = null;
	private String nowdate = "";// 记录前一天日期
	private Costeveryday oThis = this;
	MyApplication myApp;

	private ViewPager mViewPager;
	private LayoutInflater mLi;
	private View view1, view2, view3;
	private ArrayList<View> views = new ArrayList<View>();

	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int imageWidth;// 动画图片宽度
	private TextView toptitle = null;
	/**
	 * 侧滑布局对象，用于通过手指滑动将左侧的菜单布局进行显示或隐藏。
	 */
	// private SlidingLayout slidingLayout;

	private LinearLayout content;

	/**
	 * menu按钮，点击按钮展示左侧布局，再点击一次隐藏左侧布局。
	 */
	private ImageButton menuButton;

	// private GridView gridViewmain;

	Grideviewmenu gm;
	CustomProgressDialog proDialog;// 加载框
	private TextView nametv, tv;
	private Double totalprice;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.costview);

		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		myApp.getUserRecords().setUsername(myApp.getAccount());
		myApp.getUserRecords().setModule("Costeveryday@一日清单");
		UserRecord.getInstance(myApp.getUserRecords()).init();
		
		// 获取view
		findView();
		// 获取病人费用信息
		getPatInfo();
		
		
	}

	private void getPatInfo()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadPatInfo()).start();

	}

	class LoadPatInfo implements Runnable
	{

		public void run()
		{

			Looper.prepare();
			initData();
			Looper.loop();

		}

	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{

			super.handleMessage(msg);
			switch (msg.what)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					if (mainAdapter != null)
					{
						mainAdapter.notifyDataSetChanged();
					}
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Map<String, Object> map = (Map<String, Object>) msg.obj;
					listmain = (List<Map<String, Object>>) map.get("tempmain");
					children = (List<Object>) map.get("tempchildren");
					if (mainAdapter == null)
					{
						mainAdapter = new MyMainAdapter();
					}
					list_main.setAdapter(mainAdapter);
					mainAdapter.notifyDataSetChanged();
					break;

				default:
					break;
			}
		}
	};

	private void initData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			
				List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
				List<Object> tempchildren = new ArrayList<Object>();
				Map<String, Object> tempmap = new HashMap<String, Object>();
				List<NameValuePair> ls = new ArrayList<NameValuePair>();
				ls.add(new BasicNameValuePair("userid", myApp.getAccount()));
				ls.add(new BasicNameValuePair("sfzh",myApp.getSfzh()));
				ls.add(new BasicNameValuePair("zsxm",myApp.getHzxm()));
				ls.add(new BasicNameValuePair("sjh",myApp.getSjh()));
				ls.add(new BasicNameValuePair("startdate", nowdate));
				ls.add(new BasicNameValuePair("enddate", nowdate));
				ls.add(new BasicNameValuePair("sfdxmid", ""));
				JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLCOSTTADAY, ls);
				JSONArray jsonArr;
				if (json != null && !json.equals(""))
				{
					if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
					{
						if (new JSONArray(json.getString("jsonstr")).length() > 0)
						{
							jsonArr = new JSONArray(json.getString("jsonstr"));
							List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
							String sfrq_temp="",sfrq_tempx="";//记录收费日期
							String dxmid_temp="",dxmid_tempx="";//记录大项目id
							totalprice = 0.00;
							/////////////////////////////////////////////////////
							double dxmje = 0.00;//大项目金额
							String sfdw = "";
							for (int i = 0; i < jsonArr.length(); i++) {
								JSONObject obj_main = jsonArr.getJSONObject(i);
								
								totalprice += Double.valueOf(obj_main.getString("sfje"));//总金额
								dxmid_tempx = obj_main.getString("sfdxmid").toString();
								sfrq_tempx = obj_main.getString("sfrq").toString();
								Map<String, Object> map_sub = new HashMap<String, Object>();
								map_sub.put("sfxxmmc", obj_main.getString("sfxxmmc"));
								map_sub.put("sfsl", obj_main.getString("sfsl"));
								map_sub.put("sfdj", obj_main.getString("sfdj"));
								sfdw = obj_main.has("sfdw")?obj_main.getString("sfdw"):"";//单位
								map_sub.put("sfdw", sfdw);
								if(dxmid_temp.equals(dxmid_tempx)){//大项目id
									list.add(map_sub);
									dxmje += Double.valueOf(obj_main.getString("sfje"));
								}else{
									
									if(i>0){
										JSONObject obj_main_pre = jsonArr.getJSONObject(i-1);
										Map<String, Object> map_main = new HashMap<String, Object>();
										map_main.put("sfdxmmc", obj_main_pre.getString("sfdxmmc"));
										map_main.put("sfje", dxmje);
										
										if (sfrq_temp.equals(sfrq_tempx))
										{
											map_main.put("sfrq", "");
										}
										else
										{
											map_main.put("sfrq", sfrq_tempx);
											sfrq_temp = sfrq_tempx;
										}
										tempmain.add(map_main);
										tempchildren.add(list);
									}
									list = new ArrayList<Map<String, Object>>();
									list.add(map_sub);
									dxmid_temp = dxmid_tempx;
									dxmje = Double.valueOf(obj_main.getString("sfje"));
									
								}
								if(i==jsonArr.length()-1){
									Map<String, Object> map_main = new HashMap<String, Object>();
									map_main.put("sfdxmmc", obj_main.getString("sfdxmmc"));
									map_main.put("sfje", dxmje);
									if (sfrq_temp.equals(sfrq_tempx))
									{
										map_main.put("sfrq", "");
									}
									else
									{
										map_main.put("sfrq", sfrq_tempx);
										sfrq_temp = sfrq_tempx;
									}
									tempmain.add(map_main);
									tempchildren.add(list);
								}
								
							}
							msg.what = 0;
							tempmap.put("tempmain", tempmain);
							tempmap.put("tempchildren", tempchildren);
							msg.obj = tempmap;
						}
						else
						{
							msg.what = -1;
							msg.obj = "暂无数据";
						}
					}
					else
					{
						msg.what = -1;
						msg.obj = "系统错误";
					}

				}
				else
				{
					msg.what = -1;
					msg.obj = "网络连接失败!";
				}
			
				
			
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Message msg = myHandler.obtainMessage();
			msg.what = -1;
			msg.obj = e.toString();
			myHandler.sendMessage(msg);
		}
	}

	private void findView()
	{
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mLi = LayoutInflater.from(this);
		view1 = mLi.inflate(R.layout.cost_everyday, null);
		view2 = mLi.inflate(R.layout.cost_everyday, null);
		view3 = mLi.inflate(R.layout.cost_everyday, null);
		views.add(view1);
		views.add(view2);
		views.add(view3);
		mViewPager.setAdapter(mPagerAdapter);
		mViewPager.setCurrentItem(2);
		mViewPager.setOnPageChangeListener(new MyOnPagerChangeListener());
		Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
		calendar.add(Calendar.DATE, -1); // 得到前一天
		nowdate = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
		list_main = (ActionSlideExpandableListView) view3.findViewById(R.id.list);
		toptitle = (TextView) view3.findViewById(R.id.toptitle);
		toptitle.setText("一日清单(今天)");
		menuButton = (ImageButton) view3.findViewById(R.id.menuButton);
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				oThis.onBackPressed();
			}
		});
	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MyMainAdapter extends BaseAdapter
	{

		public int getCount()
		{

			return listmain.size();
		}

		public Object getItem(int position)
		{

			return listmain.get(position);
		}

		public long getItemId(int position)
		{

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{

			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_cost__main, null);

			if (map.get("sfrq").toString().equals(""))
			{
				view.findViewById(R.id.headitem).setVisibility(View.GONE);
			}
			else
			{
				TextView costtime = (TextView) view.findViewById(R.id.costtime);
				String time = map.get("sfrq").toString();
				time = time.substring(0, 4) + "-" + time.substring(4, 6) + "-" + time.substring(6, 8);
				costtime.setText(time);
				TextView totalcost = (TextView) view.findViewById(R.id.totalcost);
				totalcost.setText("收费：" + String.format("%.2f", totalprice) + "元");
			}

			TextView sfdxmmc = (TextView) view.findViewById(R.id.sfdxmmc);
			TextView sfje = (TextView) view.findViewById(R.id.sfje);
			sfdxmmc.setText(map.get("sfdxmmc").toString());
			sfje.setText(String.format("%.2f", map.get("sfje")));

			InnerListView list_sub = (InnerListView) view.findViewById(R.id.list_cost_sub);
			ScrollView scroll_view = (ScrollView) view.findViewById(R.id.scroll_view);
			listsub = (List<Map<String, Object>>) children.get(position);
			subAdapter = new MySubAdapter(oThis, listsub);
			list_sub.setAdapter(subAdapter);
			list_sub.setParentScrollView(scroll_view);
			list_sub.setMaxHeight(DisplayUtil.dip2px(oThis, 300));
			return view;
		}

	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MySubAdapter extends BaseAdapter
	{

		Context context;
		List children;

		public MySubAdapter(Context context, List children)
		{
			super();
			this.context = context;
			this.children = children;
		}

		public int getCount()
		{

			return children.size();
		}

		public Object getItem(int position)
		{

			return children.get(position);
		}

		public long getItemId(int position)
		{

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{

			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_cost_sub, null);

			item = (TextView) view.findViewById(R.id.item);
			item.setText(map.get("sfxxmmc").toString());
			
			contenttv = (TextView) view.findViewById(R.id.content);
			String dw = "";
			if(!map.get("sfdw").toString().trim().equals("")){
				dw = "("+ map.get("sfdw").toString().trim()+")";
			}
			contenttv.setText("X" + map.get("sfsl").toString()+dw);

			reference = (TextView) view.findViewById(R.id.reference);
			reference.setText(map.get("sfdj").toString());
			if(Double.valueOf(map.get("sfsl").toString())<0){
				contenttv.setTextColor(Color.RED);
				reference.setTextColor(Color.RED);
			}else{
				contenttv.setTextColor(Color.BLACK);
				reference.setTextColor(Color.BLACK);
			}
			if (position % 2 == 1)
			{
				view.setBackgroundColor(getResources().getColor(R.color.white));
			}

			return view;
		}

	}

	// 填充ViewPager的数据适配器
	PagerAdapter mPagerAdapter = new PagerAdapter()
	{

		@Override
		public boolean isViewFromObject(View arg0, Object arg1)
		{

			return arg0 == arg1;
		}

		@Override
		public int getCount()
		{
			return views.size();
		}

		@Override
		public void destroyItem(View container, int position, Object object)
		{

			((ViewPager) container).removeView(views.get(position));
		}

		@Override
		public Object instantiateItem(View container, int position)
		{

			((ViewPager) container).addView(views.get(position));

			return views.get(position);
		}

	};

	class MyOnPagerChangeListener implements ViewPager.OnPageChangeListener
	{

		public void onPageScrollStateChanged(int arg0)
		{

		}

		public void onPageScrolled(int arg0, float arg1, int arg2)
		{

		}

		public void onPageSelected(int arg0)
		{
			list_main = (ActionSlideExpandableListView) views.get(arg0).findViewById(R.id.list);
			toptitle = (TextView) views.get(arg0).findViewById(R.id.toptitle);
			if (arg0 == 0)
			{
				Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
				calendar.add(Calendar.DATE, -3); // 得到前一天
				nowdate = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
				toptitle.setText("一日清单(前天)");
			}
			else if (arg0 == 1)
			{
				Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
				calendar.add(Calendar.DATE, -2); // 得到前一天
				nowdate = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
				toptitle.setText("一日清单(昨天)");
			}
			else if (arg0 == 2)
			{
				Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
				calendar.add(Calendar.DATE, -1); // 得到前一天
				nowdate = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
				toptitle.setText("一日清单(今天)");
			}
			getPatInfo();
			menuButton = (ImageButton) views.get(arg0).findViewById(R.id.menuButton);
			menuButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					oThis.onBackPressed();
				}
			});
		}

	}
}
